# 开始跟踪: hdc shell hitrace --trace_begin app commercial ace
# 结束跟踪: hdc shell hitrace --trace_finish > P:/Python/Kea2/test.ftrace
from pathlib import Path
from kea2 import precondition, prob
from kea2.hypiumDriver import UiDriver
from kea2.traceRecorder import TraceRecorder
from kea2.hypiumUtils import get_hierarchy, max_tries

from hypium import BY
from unittest import TestCase


class PerformanceCase(TestCase):

    d: UiDriver

    @max_tries(3)
    @precondition(lambda self:
        self.d.find_component(BY.text("更多"))
    )
    def test_switch(self):
        """测试：点击更多按钮时的page切换应该短于200ms
        """
        tr = TraceRecorder(driver=self.d)
        tr.start()
        self.d.find_component(BY.text("更多")).click()
        tr.end()

        switch_dur = tr.get_duration("H:ABILITY_OR_PAGE_SWITCH")

        assert switch_dur < 0.2, "Error: switch duration is too long (>200ms)"
    
    @prob(0.2)
    @max_tries(10)
    @precondition(lambda self: True)
    def test_node_limit(self):
        """
        每帧渲染节点数量限制 (默认 500)
        https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V13/ide-render-node-limit-0430-V13
        """
        nodeCounter = NodeCounter()
        root = get_hierarchy()
        traverse_uiTree(root, nodeCounter)
        assert nodeCounter.count < 500, f"Error: too many nodes rendered ({nodeCounter.count})"


class NodeCounter:
    def __init__(self):
        self.count = 0

    def __call__(self, node_attrs):
        self.count += 1


def traverse_uiTree(node, hook):
    if hook(node["attributes"]):
        print(node)
        return True
    for child in node["children"]:
        traverse_uiTree(child, hook)